package api;

import com.fasterxml.jackson.databind.ObjectMapper;
import model.Email;
import model.MailUtil;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.Random;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: DELL
 * Date: 2023-04-02
 * Time: 21:22
 */
@WebServlet("/email")
public class EmailServlet extends HttpServlet {
    // 收到点击注册后发来的激活邮件请求, 根据用户邮箱 id发送请求
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 生成随机数
        Random random = new Random();
        int code = random.nextInt(10_00000 - 100000) + 100000; // 生成一个 六位数的随机验证码

        System.out.println(code + "这是随机产生的");
        req.setCharacterEncoding("utf8");
        resp.setContentType("application/json; charset = utf8");
        // 解析发来的发来的用户邮箱id
        ObjectMapper objectMapper = new ObjectMapper();
        // 读取请求中传来的邮箱id参数解析成 Email 对象
        Email email = objectMapper.readValue(req.getInputStream(), Email.class);

        // 判断是163邮箱还是qq邮箱
        if (email.getEmailId().contains("@qq.com")) {
            // 为QQ邮箱
            MailUtil.sendMail(email.getEmailId(), "你得验证码为: "+ code +  "请妥善保管,请勿轻易告知他人!", "欢迎注册博客!");
            resp.getWriter().write("{\"flag\":true}");

        } else if(email.getEmailId().contains("@163.com")){
            MailUtil.sendMail1(email.getEmailId(), "你得验证码为: " + code + ", 请妥善保管,请勿轻易告知他人!", "欢迎注册博客!");
            resp.getWriter().write("{\"flag\":true}");

        }else {
            // 返回状态码
            resp.getWriter().write("{\"flag\":false}");
        }
        // 建立会话
        HttpSession session = req.getSession(true);
        // 存储会话信息
        session.setAttribute("code", code);
    }
}
